#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
获取待审批列表测试脚本
"""

import requests
import json

class PendingApprovalTest:
    def __init__(self, base_url="http://localhost:5000"):
        self.base_url = base_url
        self.session = requests.Session()
        
    def login(self, username="admin", password="123456"):
        """登录获取Token"""
        print(f"🔐 登录用户: {username}")
        
        login_data = {
            "userName": username,
            "password": password
        }
        
        try:
            response = self.session.post(f"{self.base_url}/api/app/user-login/login", json=login_data)
            result = response.json()
            
            if result.get("statusCode") == 200:
                print(f"✅ 登录成功: {result.get('realName')}")
                return result.get("token")
            else:
                print(f"❌ 登录失败: {result.get('message')}")
                return None
        except Exception as e:
            print(f"❌ 登录异常: {str(e)}")
            return None
    
    def get_pending_approval_list(self, token):
        """获取待审批列表（方法一：通过审批接口）"""
        print("\n📋 方法一：通过审批接口获取待审批列表")
        
        headers = {"Authorization": f"Bearer {token}"}
        
        try:
            response = self.session.get(f"{self.base_url}/api/inbound-approval/get-pending-approval-list", headers=headers)
            result = response.json()
            
            if result.get("code") == 200:
                print(f"✅ 获取待审批列表成功")
                print(f"📊 待审批数量: {len(result.get('data', []))}")
                
                for i, item in enumerate(result.get('data', []), 1):
                    print(f"  {i}. 业务ID: {item.get('businessId')}")
                    print(f"     业务类型: {item.get('businessType')}")
                    print(f"     当前步骤: {item.get('currentStep')}")
                    print(f"     审批人: {item.get('currentApproverName')}")
                    print(f"     创建时间: {item.get('creationTime')}")
                    print()
                
                return result.get('data', [])
            else:
                print(f"❌ 获取待审批列表失败: {result.get('message')}")
                return []
        except Exception as e:
            print(f"❌ 获取待审批列表异常: {str(e)}")
            return []
    
    def get_pending_inbound_list(self, token):
        """获取待审批入库单列表（方法二：通过入库单接口）"""
        print("\n📋 方法二：通过入库单接口获取待审批列表")
        
        headers = {"Authorization": f"Bearer {token}"}
        
        try:
            response = self.session.get(f"{self.base_url}/api/app/inboundmanagement/get-pending-approval-inbound-list", headers=headers)
            result = response.json()
            
            if result.get("code") == 200:
                print(f"✅ 获取待审批入库单列表成功")
                print(f"📊 待审批入库单数量: {len(result.get('data', []))}")
                
                for i, item in enumerate(result.get('data', []), 1):
                    print(f"  {i}. 入库单号: {item.get('code')}")
                    print(f"     入库类型: {item.get('type')}")
                    print(f"     状态: {item.get('state')}")
                    print(f"     入库日期: {item.get('date')}")
                    print(f"     经办人: {item.get('manager')}")
                    print(f"     入库数量: {item.get('num')}")
                    print(f"     入库金额: {item.get('price')}")
                    print()
                
                return result.get('data', [])
            else:
                print(f"❌ 获取待审批入库单列表失败: {result.get('message')}")
                return []
        except Exception as e:
            print(f"❌ 获取待审批入库单列表异常: {str(e)}")
            return []
    
    def get_all_inbound_list(self, token):
        """获取所有入库单列表（用于对比）"""
        print("\n📋 获取所有入库单列表（用于对比）")
        
        headers = {"Authorization": f"Bearer {token}"}
        
        try:
            response = self.session.get(f"{self.base_url}/api/app/inboundmanagement/get-inbound-list?index=1&size=20", headers=headers)
            result = response.json()
            
            if result.get("code") == 200:
                data = result.get('data', {})
                print(f"✅ 获取入库单列表成功")
                print(f"📊 总数量: {data.get('totalCount', 0)}")
                print(f"📊 当前页数量: {len(data.get('pageDatas', []))}")
                
                # 按状态分组显示
                status_groups = {}
                for item in data.get('pageDatas', []):
                    state = item.get('state', 0)
                    if state not in status_groups:
                        status_groups[state] = []
                    status_groups[state].append(item)
                
                for state, items in status_groups.items():
                    state_name = {
                        1: "草稿",
                        2: "待审核", 
                        3: "驳回",
                        4: "已完成"
                    }.get(state, f"未知状态({state})")
                    
                    print(f"\n📋 {state_name} ({len(items)}个):")
                    for item in items:
                        print(f"  - {item.get('code')} ({item.get('type')}) - {item.get('manager')}")
                
                return data.get('pageDatas', [])
            else:
                print(f"❌ 获取入库单列表失败: {result.get('message')}")
                return []
        except Exception as e:
            print(f"❌ 获取入库单列表异常: {str(e)}")
            return []
    
    def run_full_test(self):
        """运行完整测试"""
        print("🚀 开始获取待审批列表测试")
        print("=" * 50)
        
        # 步骤1: 登录
        token = self.login()
        if not token:
            print("❌ 登录失败，测试终止")
            return False
        
        # 步骤2: 获取待审批列表（方法一）
        pending_approvals = self.get_pending_approval_list(token)
        
        # 步骤3: 获取待审批入库单列表（方法二）
        pending_inbounds = self.get_pending_inbound_list(token)
        
        # 步骤4: 获取所有入库单列表（对比）
        all_inbounds = self.get_all_inbound_list(token)
        
        # 步骤5: 分析结果
        print("\n📊 测试结果分析:")
        print(f"✅ 待审批工作流数量: {len(pending_approvals)}")
        print(f"✅ 待审批入库单数量: {len(pending_inbounds)}")
        print(f"✅ 总入库单数量: {len(all_inbounds)}")
        
        # 统计各状态的入库单数量
        state_counts = {}
        for inbound in all_inbounds:
            state = inbound.get('state', 0)
            state_counts[state] = state_counts.get(state, 0) + 1
        
        print("\n📈 入库单状态分布:")
        for state, count in state_counts.items():
            state_name = {
                1: "草稿",
                2: "待审核", 
                3: "驳回",
                4: "已完成"
            }.get(state, f"未知状态({state})")
            print(f"  {state_name}: {count}个")
        
        print("\n🎉 测试完成！")
        return True

def main():
    """主函数"""
    print("获取待审批列表测试工具")
    print("请确保:")
    print("1. 系统已启动 (http://localhost:5000)")
    print("2. 数据库连接正常")
    print("3. 有测试数据")
    
    test = PendingApprovalTest()
    success = test.run_full_test()
    
    if success:
        print("\n✅ 测试完成: 所有功能正常")
    else:
        print("\n❌ 测试完成: 发现问题，请检查日志")

if __name__ == "__main__":
    main() 